<?php

namespace App\Models;

use Validator;
use Illuminate\Validation\Rule;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Cate extends Model
{
    use SoftDeletes;
    protected $fillable = ['catename', 'sort'];
    protected $dateFormat = 'U';

    //关联文章模型
    public function articles()
    {
        return $this->hasMany('App\\Models\\Article', 'cate_id', 'id');
    }

    //添加
    public function add($data)
    {
        $rule = [
            'catename' => 'bail|required|unique:cates',
            'sort' => 'required|integer'
        ];

        $msg = [
            'catename.required' => '栏目名称不能为空',
            'catename.unique' => '栏目已存在',
            'sort.required' => '排序不能为空',
            'sort.integer' => '排序必须是数字'
        ];
        $validator = Validator::make($data, $rule, $msg);
        if ($validator->fails()) {
            return $validator->errors()->first();
        }
        $result = $this->create($data);
        if ($result) {
            return 1;
        }else {
            return '栏目添加失败';
        }
    }

    //排序
    public function sort($data)
    {
        $rule = [
            'sort' => 'bail|required|integer'
        ];

        $msg = [
            'sort.required' => '排序不能为空',
            'sort.integer' => '排序必须为数字'
        ];
        $validator = Validator::make($data, $rule, $msg);
        if ($validator->fails()) {
            return $validator->errors()->first();
        }
        $cateInfo = $this->find($data['id']);
        $cateInfo->sort = $data['sort'];
        $result = $cateInfo->save();
        if ($result) {
            return 1;
        }else {
            return '排序失败';
        }
    }

    //编辑
    public function edit($data)
    {
        $rule = [
            'catename' => [
                'bail',
                'required',
                Rule::unique('cates')->ignore($data['id'])
            ]
        ];

        $msg = [
            'catename.required' => '栏目名称不能为空',
            'catename.unique' => '栏目已存在'
        ];
        $validator = Validator::make($data, $rule, $msg);
        if ($validator->fails()) {
            return $validator->errors()->first();
        }
        $cateInfo = $this->find($data['id']);
        $cateInfo->catename = $data['catename'];
        $result = $cateInfo->save();
        if ($result) {
            return 1;
        }else {
            return '修改失败';
        }
    }
}
